package org.example.Utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component

@ConfigurationProperties(prefix = "oss.aliyun")
public class OSSUtil {

    //读取配置文件的内容
    private static final String endpoint = "oss-cn-beijing.aliyuncs.com";
    private static final String keyId = "LTAI5tNSfHDBRxKBUNn5oXL7";
    private static final String keySecret = "mInuvnyvVlKPtk2ewa6Qabk8nZGhf1";
    private static String bucketName = "worduniapp";

    public String upload(MultipartFile file) throws IOException {
        //创建OSSClient实例。
        OSS ossClient = new OSSClient(endpoint, keyId, keySecret);

        //获取上传文件输入流
        InputStream inputStream = file.getInputStream();
        //获取文件名称
        String fileName = file.getOriginalFilename();

        //保证文件名唯一，去掉uuid中的'-'
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        fileName = uuid + fileName;

        //把文件按日期分类，构建日期路径：avatar/2019/02/26/文件名
        //String datePath = new Date().toString("yyyy/MM/dd");
        String datePath = "2024";
        //拼接
        fileName = datePath + "/" + fileName;

        //调用oss方法上传到阿里云
        //第一个参数：Bucket名称
        //第二个参数：上传到oss文件路径和文件名称
        //第三个参数：上传文件输入流
        ossClient.putObject(bucketName, fileName, inputStream);

        //把上传后把文件url返回
        //https://xppll.oss-cn-beijing.aliyuncs.com/01.jpg
        String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
        //关闭OSSClient
        ossClient.shutdown();

        return url;


    }
}
